import React, { useMemo, memo } from 'react';
import { Category } from '@/ui-components/common';
import { dynamic } from 'umi';
import { Spin } from 'antd';

type DynamicType = {
  config: Record<string, any>;
  component: string;
  category: Category;
};
const DynamicFunc = (component: string, category: string) => {
  return dynamic({
    loader: async function () {
      const { default: Compt } = await import(
        `@/ui-components/${category}/${component}`
      );
      return (props: DynamicType) => {
        const { config } = props;
        return <Compt {...config} />;
      };
    },
    loading: () => (
      <div style={{ paddingTop: 10, textAlign: 'center' }}>
        <Spin />
      </div>
    ),
  });
};

const DynamicEngine = memo((props: DynamicType) => {
  const { component, config, category } = props;
  const Dynamic = useMemo(() => {
    return DynamicFunc(component, category) as unknown as FC<DynamicType>;
  }, [config]);

  return <Dynamic {...props} />;
});

export default DynamicEngine;
